package cn.cc.thread;

public class ConsumerAndProvider {
    public static void main(String[] args) throws Exception{
        Resource res = new Resource() ;
        SubThread sub = new SubThread(res);
        AddThread add = new AddThread(res);
        new Thread(sub,"减法线程--A ").start();
        new Thread(sub,"减法线程--B ").start();;
        new Thread(add,"加法线程--A ").start();;
        new Thread(add,"加法线程--B ").start();;
    }
}
class Resource{
    private int num = 0 ;
    private boolean flag = false ;
    public synchronized void add()throws Exception{
        if (flag == false) {
            super.wait();
        }
        Thread.sleep(100);
        this.num ++ ;
        System.out.println("【进行了加法操作 --- 】" + Thread.currentThread().getName() + "num =" + this.num);
        this.flag = false ;
        super.notifyAll();
    }
    public synchronized void sub()throws Exception{
        if (flag == true) {
            super.wait();
        }
        Thread.sleep(100);
        this.num -- ;
        System.out.println("【进行了减法操作 --- 】" + Thread.currentThread().getName() + "num =" + this.num);
        this.flag = true ;
        super.notifyAll();
    }
}
class AddThread implements Runnable {
    private Resource resource ;
    public AddThread(Resource resource ){
        this.resource = resource ;
    }
    @Override
    public void run() {
        for (int x = 0; x < 50; x++) {
            try {
                resource.add();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
class SubThread implements Runnable {
    private Resource resource ;
    public SubThread(Resource resource ){
        this.resource = resource ;
    }
    @Override
    public void run() {
        for (int x = 0; x < 50; x++) {
            try {
                resource.sub();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
